let activeEffect = null
const bucket = new WeakMap()

export function effect(fn, options={}) {
  const effectFn = ()=> {
    activeEffect = effectFn
    fn()
  }
  effectFn.options = options
  effectFn()
}


export function track(target, key) {
  if(!activeEffect) return
  let depsMap = bucket.get(target)
  if(!depsMap) {
    depsMap = new Map()
    bucket.set(target, depsMap)
  }
  let deps = depsMap.get(key)
  if(!deps) {
    deps = new Set()
    depsMap.set(key, deps)
  }
  deps.add(activeEffect)
}

export function trigger(target, key) {
  const depsMap = bucket.get(target)
  if(!depsMap) return 
  const deps = depsMap.get(key)
  deps.forEach(effectFn=> {
    if(effectFn === activeEffect) return
    const {scheduler} = effectFn.options
    if(scheduler) {
      scheduler(effectFn)
    } else {
      effectFn()
    }
  })
}